<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/2/26
 * Time: 下午4:42
 */
class Approve extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation'); //加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
        $this->load->model('goods_model');
        $this->load->model('user_model');
        $this->load->model('customer_model');
        $this->load->library('email');
    }

    //審批中心頁面
    public function index()
    {

        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];

        //获取admin下面的子辈和孙辈的(不包含自己)
        $str = $this->customer_model->get_customer_user($customer_id,1);
        
        $where = [];
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
            if ($id == 2) {
                $this->db->where('status =', 2);
                $this->db->or_where('status =', 4);
            } elseif ($id == 3) {
                $this->db->where('status =', 3);
                $this->db->or_where('status =', 5);
            } elseif ($id == "0") {
                $this->db->where('status =', 0);
            } elseif ($id == 1) {
                $this->db->where('status =', 1);
            }
        } else {
            $id = "";
        }

        //分页
        $listRows = 4; //每页数量

        $this->db->where_in('customer_id', $str);
        $count = $this->db->from('app_temp')->count_all_results();
        

        $num = $count / $listRows;

        if (floor($num) == $num) {
            $num = floor($num);
        } else {
            $num = floor($num) + 1;
        }
        if (isset($_GET['p'])) {
            $p = $_GET['p'];
        } else {
            $p = 1;
        }

        if ($p < $num) {
            $data['nexturl'] = base_url('approve/index') . '?p=' . ($p + 1) . '&id=' . $id;
            //$data['nexturl'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?p=' . ($p + 1) . '&id=' . $id;
        } else {
            $data['nexturl'] = 'javascript:;';
        }
        if ($p > 1) {
            $data['preurl'] = base_url('approve/index') . '?p=' . ($p - 1) . '&id=' . $id;
            //$data['preurl'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?p=' . ($p - 1) . '&id=' . $id;
        } else {
            $data['preurl'] = 'javascript:;';
        }

        $data['total_page'] = $num;
        $data['nowPage'] = $p;

        $firstRow = $listRows * ($p - 1);

        $where = [];
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
            if ($id == 2) {
                $this->db->or_group_start()
                ->where('status =', 2)
                ->or_where('status =', 4)
                ->group_end();
                // $this->db->where('status =', 2);
                //   $this->db->or_where('status =', 4);
            } elseif ($id == 3) {
                $this->db->or_group_start()
                ->where('status =', 3)
                ->or_where('status =', 5)
                ->group_end();
                //  $this->db->where('status =', 3);
                //   $this->db->or_where('status =', 5);

            } elseif ($id == "0") {
                $this->db->where('status =', 0);
            } elseif ($id == 1) {
                $this->db->where('status =', 1);
            }
        } else {
            $id = "";
        }

        $this->db->where_in('customer_id', $str);


        $field = '*,
        (select username from app_customer where app_customer.id = app_temp.customer_id) as customer_name,
        (select order_bn from app_order where app_order.shop_order_id = app_temp.shop_order_id) as shop_order_bn,
        (select tel from app_customer where app_customer.id = app_temp.customer_id) as customer_tel,
        (select reason from app_temp_approval where app_temp_approval.temp_id = app_temp.id AND app_temp_approval.verify_status=2) as approve_reason,
        (select name from app_cost_center where app_cost_center.id = app_temp.cost_center_id) as cost_center_name';
        $data['list'] = $this->db->select($field)->from('app_temp')->order_by('alert_time', 'desc')->order_by('id', 'desc')->limit($listRows, $firstRow)->get()->result_array();
        foreach ($data['list'] as $key => $value) {
            //等待时间
            $data['list'][$key]['wait_time'] = wait_time($value['created_at']);
        }
        $data['id'] = $id;
        $data['p'] = $p;
        $data['identity'] = $identity;
        $this->load->view('approve/index', $data);
    }

    //审批订单详情
    public function detail()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
        } else {
            $id = '';
        }
        //获取用户子辈或孙子辈
        $str = $this->customer_model->get_customer_user($customer_id,1);

        //获取审批订单的用户
        $where = array('id' => $id);
        $field = 'customer_id,
        (SELECT parent_id FROM app_customer WHERE app_customer.id=app_temp.customer_id) AS cus_parent_id,
        (SELECT identity FROM app_customer WHERE app_customer.id=app_temp.customer_id) AS cus_identity';
        $temp_order = $this->db->where($where)->select($field)->from('app_temp')->get()->row_array();
        if (!in_array($temp_order['customer_id'], $str)) {
            exit('需要审批的订单不存在');
        }

        $arr_user = $this->customer_model->get_admin_customer($temp_order['customer_id']);
        if (!$arr_user) {
            exit('操作失败');
        }

        $field = 'id,customer_id,money,address_id,invoice_id,detail,status,reason,remark,update_at,express_fee,created_at,content,
        (SELECT name FROM app_address WHERE app_address.id=app_temp.address_id) AS address_name,
        (SELECT province FROM app_address WHERE app_address.id=app_temp.address_id) AS address_province,
        (SELECT city FROM app_address WHERE app_address.id=app_temp.address_id) AS address_city,
        (SELECT district FROM app_address WHERE app_address.id=app_temp.address_id) AS address_district,
        (SELECT postcode FROM app_address WHERE app_address.id=app_temp.address_id) AS address_postcode,
        (SELECT phone FROM app_address WHERE app_address.id=app_temp.address_id) AS address_phone,
        (SELECT address FROM app_address WHERE app_address.id=app_temp.address_id) AS address_address,

        (SELECT invoice_company_name FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_company_name,
        (SELECT invoice_tel FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_tel,
        (SELECT invoice_code FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_code,
        (SELECT invoice_bank FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_bank,
        (SELECT invoice_account FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_account,
        (SELECT invoice_address FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_address,
        (SELECT invoice_type FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_type';
        $data['result'] = $this->db->select($field)->get_where('app_temp', array('id' => $id, 'customer_id' => $temp_order['customer_id']))->row_array();

        $data['wait_time'] = wait_time($data['result']['update_at']);

        $data['detail'] = json_decode($data['result']['detail'], true);

        if (!$data['result']) {
            exit('需要审批的订单不存在');
        }

        if ($temp_order['cus_identity'] == 2) {
            $parent_info = $this->customer_model->get_parent_info($temp_order['customer_id']);
            $data['parent_name'] = $parent_info['username'];
            $data['parent_email'] = $parent_info['email'];
            $data['parent_id'] = $parent_info['id'];
            $where = array('temp_id' => $data['result']['id'], 'identity' => 1);
            $res = $this->db->select("id,verify_status,remark,reason")->where($where)->get('app_temp_approval')->row_array();

            if ($res) {
                $data['remark'] = $res['remark'];
                $data['reason'] = $res['reason'];
            } else {
                $data['remark'] = "";
                $data['reason'] = "";
            }

        }

        if ($temp_order['cus_identity'] == 3) {

            $parent_info = $this->customer_model->get_parent_info($temp_order['customer_id']);
            if ($parent_info['status'] == 0) {
                if ($data['result']['status'] == 0) {
                    $data['parent_name'] = "";
                } elseif ($data['result']['status'] == 4 || $data['result']['status'] == 5) {
                    $where = array('temp_id' => $data['result']['id'], 'identity' => 1);
                    if(count($arr_user) == 2){
                        $data['parent_name'] = $arr_user[1]['username'];
                        $data['parent_email'] = $arr_user[1]['email'];
                        $data['parent_id'] = $arr_user[1]['id'];
                    }else{
                        $data['parent_name'] = $arr_user[0]['username'];
                        $data['parent_email'] = $arr_user[0]['email'];
                        $data['parent_id'] = $arr_user[0]['id'];
                    }
                } else {
                    $where = array('temp_id' => $data['result']['id']);
                    if(count($arr_user) == 2){
                        $data['parent_name'] = $arr_user[1]['username'];
                    }else{
                        $data['parent_name'] = $arr_user[0]['username'];
                    }
                    
                }
                $res = $this->db->select("id,verify_status,remark,reason")->where($where)->order_by("id", "desc")->get('app_temp_approval')->row_array();
                if ($res) {
                    $data['remark'] = $res['remark'];
                    $data['reason'] = $res['reason'];
                } else {
                    $data['remark'] = "";
                    $data['reason'] = "";
                }
            } else {
                if ($data['result']['status'] == 0) {
                    $data['parent_name'] = "";
                } elseif ($data['result']['status'] == 2 || $data['result']['status'] == 3) {
                    $where = array('temp_id' => $data['result']['id'], 'identity' => 2);
                    $data['parent_name'] = $arr_user[0]['username'];
                    $data['parent_email'] = $arr_user[0]['email'];
                    $data['parent_id'] = $arr_user[0]['id'];
                } elseif ($data['result']['status'] == 4 || $data['result']['status'] == 5) {
                    $where = array('temp_id' => $data['result']['id'], 'identity' => 1);

                    if(count($arr_user) == 2){
                        $data['parent_name'] = $arr_user[1]['username'];
                        $data['parent_email'] = $arr_user[1]['email'];
                        $data['parent_id'] = $arr_user[1]['id'];
                    }else{
                        $data['parent_name'] = $arr_user[0]['username'];
                        $data['parent_email'] = $arr_user[0]['email'];
                        $data['parent_id'] = $arr_user[0]['id'];
                    }
                } else {
                    $where = array('temp_id' => $data['result']['id']);
                    $res = $this->db->select("id")->where($where)->get('app_temp_approval')->result_array();
                    if (count($res) == 1) {
                        $data['parent_name'] = $arr_user[0]['username'];
                    } else {
                        if(count($arr_user) == 2){
                            $data['parent_name'] = $arr_user[1]['username'];
                        }else{
                            $data['parent_name'] = $arr_user[0]['username'];
                        }
                    }
                }

                $res = $this->db->select("id,verify_status,remark,reason")->where($where)->order_by("id", "desc")->get('app_temp_approval')->result_array();
                if ($res) {
                    $data['remark'] = $res[0]['remark'];
                    $data['reason'] = $res[0]['reason'];
                } else {
                    $data['remark'] = "";
                    $data['reason'] = "";
                }
            }
        }

        $where = array('temp_id' => $_GET['id']);
        $data['temp_reason'] = "";
        $data['out_single'] = $this->db->select("out_single_product_ids")->where($where)->get('app_temp_single_budget')->row_array();
        if ($data['out_single']) {
            $out_single_ids = "";
            foreach (unserialize($data['out_single']['out_single_product_ids']) as $key => $value) {
                $out_single_ids .= ',' . $key;
            }
            $out_single_ids_str = mb_substr($out_single_ids, 1, strlen($out_single_ids));

            $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
            $data['out_single_goods'] = $this->goods_model->company_goods_infoes($out_single_ids_str,$admin_shop_user_id);
            

            $data['temp_reason'] .= '单品超出预算,';
        }

        $data['out_month'] = $this->db->select("exceed_budget")->where($where)->get('app_temp_month_budget')->row_array();
        if ($data['out_month']) {
            $data['temp_reason'] .= '订单超出预算,';
        }

        $data['out_list'] = $this->db->select("out_list_product_ids")->where($where)->get('app_temp_out_list')->row_array();
        if ($data['out_list']) {
            $out_list_ids_str = unserialize($data['out_list']['out_list_product_ids']);

            $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
            $data['out_list_goods'] = $this->goods_model->company_goods_infoes($out_list_ids_str,$admin_shop_user_id);

            $data['temp_reason'] .= '商品超出选购范围,';
        }
        $data['identity'] = $identity;

        $this->load->view('approve/detail', $data);
    }

    //订单驳回
    public function cancel()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        $post = $this->input->post();
        $id = $post['id'];
        if ($identity == 1) {
            $data['status'] = 5;
        } elseif ($identity == 2) {
            $data['status'] = 3;
        }
        if (!$id) {
            send_json(array('code' => -1, 'data' => '', 'msg' => '审批订单不存在'));
        }
        $this->db->where('id=', $id);
        $res = $this->db->update('app_temp', $data);
        if ($res) {
            $where = array(
                'temp_id' => $id,
                'parent_id' => $customer_id,
                'identity' => $identity
            );
            $row = $this->db->where($where)->from('app_temp_approval')->get()->row_array();
            if ($row) {
                //修改app_temp_approval
                $this->db->update('app_temp_approval', array('verify_status' => 2, 'reason' => $post['content'], 'updated_at' => date("Y-m-d H:i:s", time())));
            } else {
                //添加app_temp_approval
                $temp['temp_id'] = $id;
                $temp['parent_id'] = $customer_id;
                $temp['verify_status'] = 2;
                $temp['reason'] = $post['content'];
                $temp['updated_at'] = date("Y-m-d H:i:s", time());
                $temp['created_at'] = date("Y-m-d H:i:s", time());
                $temp['identity'] = $identity;
                $this->db->insert('app_temp_approval', $temp);
            }
            send_json(array('code' => 0, 'data' => '', 'msg' => '已驳回'));
        }
        send_json(array('code' => -1, 'data' => '', 'msg' => '操作失败'));
    }

    //判断是否需要提交上级审批
    public function judge()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        $post = $this->input->post();

        $id = $post['id'];
        if (!$id) {
            send_json(array('code' => -2, 'data' => '', 'msg' => '审批订单不存在'));
        }
        $where = array('id' => $id);
        if ($identity == 1) {
            $status = 1;
        } elseif ($identity == 2) {
            //默认status状态为1
            $status = 1;
            //获取manager单品商品额度/每月额度
            $quota = $this->customer_model->u_m_single_quota($customer_id);
            $single_quota = $quota['single_quota'];
            $total_quota = $quota['total_quota'];

            $temp_order = $this->db->where($where)->from('app_temp')->get()->row_array();
            if ($total_quota != 0) {
                //获取manager每月所剩的账期额度
                $total_quota_left = $this->customer_model->member_total_quota_left_month($customer_id, $identity);
                if ($temp_order['money'] > $total_quota_left) {
                    $status = 4;
                }
            }

            //获取manager用户清单id
            $list_id = $this->customer_model->u_m_list_goods_ids($customer_id);

            $goods = json_decode($temp_order['detail'], true);
            foreach ($goods['products'] as $k => $v) {
                if ($list_id) {
                    if (!in_array($v['product_id'], $list_id)) {
                        $status = 4;
                    }
                    if ($single_quota != 0) {
                        if ($v['final_price'] > $single_quota) {
                            $status = 4;
                        }
                    }
                }
            }
        }
        if($status == 1){
            send_json(array('code' => 0, 'data' => 1, 'msg' => '直接审核'));
        }else{
            send_json(array('code' => 1, 'data' => 4, 'msg' => '提交上级审核'));
        }
    }

    //订单同意
    public function agree()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        $post = $this->input->post();

        $id = $post['id'];
        if (!$id) {
            send_json(array('code' => -1, 'data' => '', 'msg' => '审批订单不存在'));
        }
        $where = array('id' => $id);

        $data['status'] = $post['status'];

        $res = $this->db->where($where)->update('app_temp', $data);

        if ($res) {
            $where = array(
                'temp_id' => $id,
                'parent_id' => $customer_id,
                'identity' => $identity
            );
            $row = $this->db->where($where)->from('app_temp_approval')->get()->row_array();
            if ($row) {
                //修改app_temp_approval
                $this->db->update('app_temp_approval', array('verify_status' => 1, 'updated_at' => date("Y-m-d H:i:s", time())));
            } else {
                //添加app_temp_approval
                $temp['temp_id'] = $id;
                $temp['parent_id'] = $customer_id;
                $temp['verify_status'] = 1;
                $temp['updated_at'] = date("Y-m-d H:i:s", time());
                $temp['created_at'] = date("Y-m-d H:i:s", time());
                $temp['identity'] = $identity;
                $this->db->insert('app_temp_approval', $temp);
            }

            if ($data['status'] == 1) {

                $where = array('id' => $id);
                $temp_order = $this->db->where($where)->from('app_temp')->get()->row_array();
                //获取发票类型
                $where = array('id' => $temp_order['invoice_id']);
                $type = $this->db->where($where)->select('invoice_type')->from('app_invoice')->get()->row_array();
                if ($type) {
                    $temp_order['type'] = $type['invoice_type'];
                } else {
                    $temp_order['type'] = "";
                }

                //获取商城地址id
                $where = array('id' => $temp_order['address_id']);
                $address = $this->db->where($where)->select('shop_id')->from('app_address')->get()->row_array();
                if ($address) {
                    $temp_order['address'] = $address['shop_id'];
                } else {
                    $temp_order['address'] = 0;
                }

                //获取商城用户id
                $shop_user_id = $this->user_model->customer_id_to_shop_user_id($temp_order['customer_id']);


                $details = json_decode($temp_order['detail'], true);
                $goods_list = array();
                if ($details && count($details)) {
                    foreach ($details['products'] as $product) {
                        $goods_list[$product['product_id']]['product_id'] = $product['product_id'];
                        $goods_list[$product['product_id']]['number'] = $product['count'];
                    }
                }

                if (!count($goods_list)) {
                    send_json(array('code' => -1, 'data' => '', 'msg' => '审批订单出现错误'));
                }

                $url = $this->config->item('shop_url') . "companymanagerapi/company_push_carts/";
                $data_arr['time'] = time();
                $data_arr['key'] = md5($this->config->item('token_const_wjyh') . $data_arr['time']);
                $data_arr['shop_user_id'] = $shop_user_id;
                $data_arr['goods_list'] = json_encode($goods_list);
                $res = json_decode(curl_request($url, $data_arr), true);

                if ($res['code'] != 200) {
                    send_json(array('code' => -1, 'data' => '', 'msg' => $res['msg']));
                }

                $url = $this->config->item('shop_url') . 'companymanagerapi/companyCreateOrder/';

                $data_arr = array();
                $data_arr['buyerId'] = $shop_user_id;
                $data_arr['addressId'] = $temp_order['address'];
                $data_arr['invoice_id'] = $temp_order['invoice_id'] ? $temp_order['invoice_id'] : "";
                $data_arr['invoice_cont'] = "";
                $data_arr['type'] = $temp_order['type'] ? $temp_order['type'] : "";
                $data_arr['time'] = time();
                $data_arr['key'] = md5($this->config->item("token_const_wjyh") . $data_arr['time']);

                $rs = curl_request($url, $data_arr);
                $result = json_decode($rs, true);

                if ($result['code'] == 200) {
                    $re = $this->db->query("select query_admin_id('" . $temp_order['customer_id'] . "') as admin_id")->row_array();
                    $where = array('customer_id' => $temp_order['customer_id'], 'shop_order_id' => $result['data']['order_id'][0]);
                    sleep(2);
                    $order_result = $this->db->where($where)->update('app_order', array('payment_url' => $result['data']['url'], 'admin_customer_id' => $re['admin_id'], 'cost_center_id' => $temp_order['cost_center_id']));
                    $temp_result = $this->db->where(array('id' => $id))->update('app_temp', array('shop_order_id' => $result['data']['order_id'][0]));
                    if ($order_result && $temp_result) {
                        send_json(array('code' => 0, 'data' => '', 'msg' => '已通过'));
                    }
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => $result['msg']));
                }
            } else {
                send_json(array('code' => 1, 'data' => '', 'msg' => '提交admin审核'));
            }
        }
        send_json(array('code' => -1, 'data' => '', 'msg' => '操作失败'));

    }

}
